<template>
  <div class="zh-organization-single organizational-s">
    <nav-header></nav-header>
    <div class="zh-table">
      <div class="zh-table-open clear">
        <div class="zh-open-right fr">
          <el-button type="primary" @click="batchImport">批量导入</el-button>
          <el-button type="primary" @click="getOrgData">刷新</el-button>
        </div>
      </div>
      <div
        class="zh-tree-contents"
        v-loading="loading.status"
        :element-loading-text="loading.txt"
      >
        <div class="frame-manage">
          <ul class="frame-list">
            <li>
              <div class="ellips">序号</div>
            </li>
            <li>
              <div class="ellips">分类名</div>
            </li>
            <li>
              <div class="ellips">操作</div>
            </li>
          </ul>
          <el-tree
            :data="orgData"
            node-key="id"
            default-expand-all
            @node-click="bindTempOrg"
          >
            <div class="custom-tree-node" slot-scope="{ node, data }">
              <ul class="frame-list">
                <li>
                  <div class="ellips">{{ orgData[0].inx++ }}</div>
                </li>
                <li>
                  <div class="ellips">
                    <span v-show="node.level >= 2" class="gap"></span
                    ><span v-show="node.level >= 3" class="gap"></span
                    ><span v-show="node.level >= 4" class="gap"></span
                    ><img
                      :src="'/static/image/user/tree' + node.level + '.png'"
                    />
                    <span v-html="data.name"></span>
                  </div>
                </li>
                <li>
                  <div class="ellips">
                    <el-button
                      type="text"
                      size="mini"
                      @click.stop="editSchoolTigger(data)"
                      v-if="parseInt(data.level) === 1"
                      >编辑</el-button
                    >
                    <el-button
                      type="text"
                      size="mini"
                      @click.stop="addFacultyTrigger(data, '添加学段')"
                      v-if="
                        parseInt(data.level) === 1 && parseInt(zeroneFlag) === 1
                      "
                      >添加学段</el-button
                    >
                    <el-button
                      type="text"
                      size="mini"
                      @click.stop="addFacultyTrigger(data, '编辑学段')"
                      v-if="
                        parseInt(data.level) === 2 && parseInt(zeroneFlag) === 1
                      "
                      >编辑</el-button
                    >
                    <el-button
                      type="text"
                      size="mini"
                      @click.stop="addGradeFlagTrigger(data, '添加年级')"
                      v-if="
                        parseInt(data.level) === 2 && parseInt(zeroneFlag) === 1
                      "
                      >添加年级</el-button
                    >
                    <el-button
                      type="text"
                      size="mini"
                      @click.stop="addGradeFlagTrigger(data, '编辑年级')"
                      v-if="
                        parseInt(data.level) === 3 && parseInt(zeroneFlag) === 1
                      "
                      >编辑</el-button
                    >
                    <el-button
                      type="text"
                      size="mini"
                      @click.stop="saveBox(data, '添加班级')"
                      v-if="
                        parseInt(data.level) === 3 && parseInt(zeroneFlag) === 1
                      "
                      >添加班级</el-button
                    >
                    <el-button
                      type="text"
                      size="mini"
                      @click.stop="saveBox(data, '编辑班级')"
                      v-if="parseInt(data.level) === 4"
                      >编辑</el-button
                    >
                    <el-button
                      type="text"
                      size="mini"
                      v-if="parseInt(data.status) === 2"
                      class="delete-button"
                      @click.stop="changeOrg_confirm(data, 1)"
                      >已禁用</el-button
                    >
                    <el-button
                      type="text"
                      size="mini"
                      v-if="parseInt(data.status) === 1"
                      @click.stop="changeOrg_confirm(data, 2)"
                      >已启用</el-button
                    >
                    <el-button
                      type="text"
                      size="mini"
                      class="delete-button"
                      @click.stop="deleteOrg(data)"
                      v-if="parseInt(data.level) !== 1"
                      >删除</el-button
                    >
                  </div>
                </li>
              </ul>
            </div>
          </el-tree>
        </div>
      </div>
    </div>
    <!-- 添加/编辑班级 -->
    <el-dialog
      :title="classTitle"
      :visible.sync="addClass"
      class="addClass"
      width="33%"
      :close-on-click-modal="false"
      @close="handleClose"
    >
      <el-form
        :model="addForm"
        ref="addForm"
        :rules="rules"
        status-icon
        label-position="left"
        label-width="130px"
      >
        <el-form-item label="请输入班级名称" prop="name">
          <el-input
            v-model.trim="addForm.name"
            placeholder="请输入班级名称"
            autocomplete="off"
            maxlength="20"
            clearable
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelClass">取消</el-button>
        <el-button type="primary" @click="saveOrg">确定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑学校 -->
    <el-dialog
      title="编辑学校"
      :visible.sync="editSchoolFlag"
      width="33%"
      :close-on-click-modal="false"
    >
      <el-form
        :model="editSchoolForm"
        ref="editSchoolForm"
        :rules="rules"
        label-position="left"
        label-width="130px"
      >
        <el-form-item label="请输入学校名称" prop="name">
          <el-input
            v-model.trim="editSchoolForm.name"
            placeholder="请输入学校名称"
            maxlength="20"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editSchool">确定</el-button>
      </div>
    </el-dialog>

    <!-- 添加/编辑 学段 ------------------------------------------------ 弹窗 -->
    <el-dialog
      :title="cat_Faculty"
      :visible.sync="addFacultyFlag"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="handleClose"
      width="33%"
    >
      <el-form
        ref="addFacultyForm"
        :model="addFacultyForm"
        :rules="rules"
        label-width="120px"
        @submit.native.prevent
      >
        <el-form-item prop="staryname" label="请输入学段">
          <el-input
            type="text"
            placeholder="请输入学段名称"
            v-model.trim="addFacultyForm.staryname"
            maxlength="20"
          >
          </el-input>
          <!-- <el-select v-model="addFacultyForm.staryname" placeholder="请选择添加的学段" >
                <el-option label="小学" value="小学">小学</el-option>
                <el-option label="初中" value="初中">初中</el-option>
                <el-option label="高中" value="高中">高中</el-option>
                <el-option label="大学" value="大学">大学</el-option>
            </el-select> -->
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addFacultyTips()">取 消</el-button>
        <el-button type="primary" @click="addFacultyTips(1)">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加/编辑 学段 ------------------------------------------------ 弹窗 -->

    <!-- 添加/编辑 年级/专业 ------------------------------------------------ 弹窗 -->
    <el-dialog
      :title="gradeEven"
      :visible.sync="addGradeFlag"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="handleClose"
      width="33%"
    >
      <el-form
        ref="addGradeForm"
        :model="addGradeForm"
        :rules="rules"
        label-width="120px"
        @submit.native.prevent
      >
        <el-form-item label="输入年级：" prop="gradename">
          <el-input
            type="text"
            placeholder="请输入年级名称"
            v-model.trim="addGradeForm.gradename"
            maxlength="20"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addGradeTips()">取 消</el-button>
        <el-button type="primary" @click="addGradeTips(1)">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加/编辑 年级/专业 ------------------------------------------------ 弹窗 -->
  </div>
</template>
<script>
export default {
  data() {
    return {
      zeroneFlag: "", // 1为允许编辑 2为禁止
      addGradeFlag: false, // 年级
      gradeEven: "",
      addGradeForm: {
        is_edit: 0,
        gradename: "", // 年级名称
        pid: "",
        level: "",
        status: "",
        app_code: ""
      },
      cat_Faculty: "",
      FacultyTitle: "",
      FacultyName: "",
      addFacultyFlag: false,
      addFacultyForm: {
        staryname: "", // 学段名称
        status: "",
        level: "",
        pid: "",
        is_edit: 0
      },
      editSchoolFlag: false, // 编辑学校弹窗
      editSchoolForm: {
        // 编辑学校
        id: 0,
        pid: 0,
        level: 0,
        base_id: 0,
        name: "",
        status: 0,
        is_edit: 0
      },
      loading: {
        status: false,
        txt: "获取数据..."
      },
      addClass: false, //弹框状态
      addForm: {
        //表单数据
        id: 0,
        pid: 0,
        level: 4,
        base_id: 0,
        name: "",
        status: 0,
        is_edit: 0
      },
      classTitle: "",
      rules: {
        name: [
          // 学校
          { validator: this.checkValue, trigger: "change", required: true },
          {
            pattern: this.rules.chinese.reg,
            message: this.rules.chinese.msg,
            trigger: "blur"
          }
        ],
        staryname: [
          { message: "请输入学段", validator: this.checkValue },
          {
            pattern: this.rules.chinese.reg,
            message: this.rules.chinese.msg,
            trigger: "blur"
          }
        ],
        gradename: [
          { message: "请输入年级", validator: this.checkValue },
          {
            pattern: this.rules.chinese.reg,
            message: this.rules.chinese.msg,
            trigger: "blur"
          }
        ]
      },
      orgData: [], //组织架构数据
      orgParam: {
        //获取组织架构参数
        data_type: "manage_tree",
        status: [1, 2]
      },
      status_arr: { 1: "启用", 2: "禁用" }, //状态数组
      addOrgStatus: true, //用于区分是添加还是修改组织架构
      treeConfig: {
        showTitleColumn: [
          { column: "name", text: "名称", style: { width: "60%" } },
          { column: "status", text: "状态", style: { width: "20%" } }
        ]
      },
      class_list: []
    };
  },
  created() {
    this.getOrgData();
    this.getEditOrder();
  },
  methods: {
    batchImport() {
      this.$router.push("/user/org/importmore");
    },
    handleClose() {
      this.addForm.name = "";
      this.addFacultyForm.staryname = ""; // 学段名称
      this.addGradeForm.gradename = ""; // 年级名称
      this.$refs.addFacultyForm && this.$refs.addFacultyForm.clearValidate();
      this.$refs.addGradeForm && this.$refs.addGradeForm.clearValidate();
      this.$refs.addForm && this.$refs.addForm.clearValidate();
    },
    checkValue(rule, value, callback) {
      if (!checkSpace(value)) {
        callback(new Error("请输入有效值"));
      } else {
        callback();
      }
    },
    getEditOrder() {
      // 判断该平台是否可以编辑组织结构
      let success = res => {
        this.zeroneFlag = res.data;
      };
      this.$ajax.get("appapi/login/check_open_org_edit", { func: { success } });
    },

    getOrgData() {
      // 获取组织架构
      this.loading.status = true;
      // 重写成功回调
      let success = data => {
        this.loading.status = false;
        this.orgData = data.data;
        if (this.orgData.length > 0) {
          this.orgData[0].inx = 1;
        }
        this.$forceUpdate(); //强制渲染
      };

      let fail = data => {
        this.loading.status = false;
        this.$message.error(data.msg);
      };
      this.$ajax.get("api/org/org", {
        params: this.orgParam,
        func: { success: success, fail: fail }
      });
    },

    editSchoolTigger(obj) {
      // 编辑学校弹窗
      this.editSchoolForm = {
        base_id: obj.base_id,
        status: obj.status,
        id: obj.id,
        pid: obj.pid,
        name: obj.name,
        level: obj.level
      };
      this.editSchoolFlag = true;
    },
    editSchool() {
      // 编辑学校
      let success = res => {
        this.$message.success(res.msg);
        this.editSchoolForm.name = "";
        this.editSchoolFlag = false;
        this.getOrgData();
      };
      let fail = res => {
        this.$message.error(res.msg);
      };
      this.$refs[`editSchoolForm`].validate(valid => {
        if (this.zeroneFlag == 1) {
          this.editSchoolForm.is_edit = 1;
        }
        if (valid) {
          this.$ajax.put("api/org/org", this.editSchoolForm, {
            func: { success, fail }
          });
        }
      });
    },

    /** 添加学段 */
    addFacultyTrigger(obj, even) {
      this.$refs.addFacultyForm && this.$refs.addFacultyForm.clearValidate();

      this.addFacultyFlag = true;
      this.cat_Faculty = even;
      if (even == "添加学段") {
        this.addFacultyForm = {
          status: obj.status,
          pid: obj.id,
          level: 2,
          base_id: 0
        };
      } else {
        this.addFacultyForm = {
          staryname: obj.name,
          id: obj.id,
          status: obj.status,
          pid: obj.pid,
          level: 2,
          base_id: 0
        };
      }
    },
    addFacultyTips(flag) {
      if (flag) {
        this.$refs[`addFacultyForm`].validate(valid => {
          if (valid) {
            if (this.cat_Faculty === "添加学段") {
              this.addFaculty();
            } else if (this.cat_Faculty === "编辑学段") {
              this.editFaculty();
            }
          } else {
            return;
          }
        });
      } else {
        this.addFacultyWinHide();
      }
    },
    addFaculty() {
      /**添加学段/院系/类别 */
      let params = {
        name: this.addFacultyForm.staryname,
        pid: this.addFacultyForm.pid,
        level: this.addFacultyForm.level,
        status: this.addFacultyForm.status,
        base_id: this.addFacultyForm.base_id
      };
      const success = res => {
        this.$message.success(res.msg);
        this.addFacultyWinHide();
        this.getOrgData();
      };
      const fail = res => {
        this.$message.error(res.msg);
      };
      this.$ajax.post("api/org/org", params, { func: { success, fail } });
    },
    editFaculty() {
      if (this.zeroneFlag == 1) {
        this.addFacultyForm.is_edit = 1;
      }
      let params = {
        name: this.addFacultyForm.staryname,
        pid: this.addFacultyForm.pid,
        id: this.addFacultyForm.id,
        level: this.addFacultyForm.level,
        status: this.addFacultyForm.status,
        base_id: this.addFacultyForm.base_id,
        is_edit: this.addFacultyForm.is_edit
      };
      const success = res => {
        this.$message.success(res.msg);
        this.addFacultyWinHide();
        this.getOrgData();
      };
      const fail = res => {
        this.$message.error(res.msg);
      };
      this.$ajax.put("api/org/org", params, { func: { success, fail } });
    },
    addFacultyWinHide() {
      /**清除输入框内容，关闭弹窗 */
      this.addFacultyForm.staryname = "";
      this.$refs.addFacultyForm && this.$refs.addFacultyForm.clearValidate();
      this.addFacultyFlag = false;
    },
    /**学段-----------------end */

    /**添加年级 */
    addGradeFlagTrigger(obj, even) {
      this.addGradeFlag = true;
      this.$refs.addGradeForm && this.$refs.addGradeForm.clearValidate();
      this.gradeEven = even;

      if (even === "添加年级") {
        this.addGradeForm = {
          pid: obj.id,
          level: 3,
          status: obj.status,
          app_code: obj.app_code,
          base_id: 0
        };
      } else {
        this.addGradeForm = {
          gradename: obj.name,
          id: obj.id,
          pid: obj.pid,
          level: obj.level,
          status: obj.status,
          base_id: 0
        };
      }
    },
    addGradeTips(flag) {
      /**控制添加/ 编辑 年级 弹窗 */
      if (flag) {
        this.$refs[`addGradeForm`].validate(valid => {
          if (valid) {
            if (this.gradeEven === "添加年级") {
              this.addGrade();
            } else {
              this.editGrade();
            }
          } else {
            return;
          }
        });
      } else {
        this.addGradeWinHide();
      }
    },
    addGrade() {
      /**添加年级 */
      let params = {
        name: this.addGradeForm.gradename,
        pid: this.addGradeForm.pid,
        level: this.addGradeForm.level,
        status: this.addGradeForm.status,
        app_code: this.addGradeForm.app_code,
        base_id: this.addGradeForm.base_id
      };
      const success = res => {
        this.$message.success(res.msg);
        this.addGradeWinHide();
        this.getOrgData();
      };
      const fail = res => {
        this.$message.error(res.msg);
      };
      this.$ajax.post("api/org/org", params, { func: { success, fail } });
    },
    editGrade() {
      /**编辑年级 */
      if (this.zeroneFlag == 1) {
        this.addGradeForm.is_edit = 1;
      }
      let params = {
        id: this.addGradeForm.id,
        name: this.addGradeForm.gradename,
        pid: this.addGradeForm.pid,
        level: this.addGradeForm.level,
        status: this.addGradeForm.status,
        base_id: this.addGradeForm.base_id,
        is_edit: this.addGradeForm.is_edit
      };
      const success = res => {
        this.$message.success(res.msg);
        this.addGradeWinHide();
        this.getOrgData();
      };
      const fail = res => {
        this.$message.error(res.msg);
      };
      this.$ajax.put("api/org/org", params, { func: { success, fail } });
    },
    addGradeWinHide() {
      /**清除输入框内容，关闭弹窗 */
      this.addGradeForm.gradename = "";
      this.$refs.addGradeForm && this.$refs.addGradeForm.clearValidate();
      this.addGradeFlag = false;
    },

    saveBox(obj, even) {
      // 添加班级/编辑班级
      console.log(obj, even);

      this.classTitle = even;
      if (even == "添加班级") {
        this.addForm = {
          base_id: 0,
          status: obj.status,
          pid: obj.id,
          level: 4
        };
      } else {
        this.addForm = {
          base_id: 0,
          status: obj.status,
          id: obj.id,
          pid: obj.pid,
          name: obj.name,
          level: 4
        };
      }
      this.addClass = true;
    },
    saveOrg() {
      this.$refs["addForm"].validate(valid => {
        if (valid) {
          let success = data => {
            this.$message.success(data.msg);
            this.addForm.name = "";
            this.$refs.addForm && this.$refs.addForm.clearValidate();
            this.addClass = false;
            this.getOrgData();
          };
          //执行请求，并将回调方法变成config成员以便鉴权过期可以执行
          if (!is_empty(this.addForm.id) && parseInt(this.addForm.id) > 0) {
            if (this.zeroneFlag == 1) {
              this.addForm.is_edit = 1;
            }
            this.$ajax.put("api/org/org", this.addForm, {
              func: { success: success }
            });
          } else {
            this.$ajax.post("api/org/org", this.addForm, {
              func: { success: success }
            });
          }
        } else {
          return;
        }
      });
    },
    cancelClass() {
      this.addForm.name = "";
      this.$refs.addForm && this.$refs.addForm.clearValidate();
      this.addClass = false;
    },

    async deleteOrg(obj) {
      // console.log("---obj", obj);
      // 删除组织架构
      if (obj.level === 4) {
        // 查询是否存在课表数据
        let power = await this.getPowerDelect(obj.id);
        if (!power) {
          let yes = data => {
            let success = data => {
              this.$message.success(data.msg);
              this.getOrgData();
            };
            this.$ajax.delete("api/org/org", {
              params: { id: obj.id },
              func: { success: success }
            });
          };
          let cancel = data => {};
          this.e_confirm({
            yes: yes,
            cancel: cancel,
            txt: "确定将 " + obj.rename + " 删除吗？"
          });
        } else {
          this.$alert(
            obj.rename + " 当前存在课表数据，请清空课表才能删除科目。",
            "提示",
            {
              confirmButtonText: "确定",
              callback: action => {}
            }
          );
        }
      } else {
        let yes = data => {
          let success = data => {
            this.$message.success(data.msg);
            this.getOrgData();
          };
          this.$ajax.delete("api/org/org", {
            params: { id: obj.id },
            func: { success: success }
          });
        };
        let cancel = data => {};
        this.e_confirm({
          yes: yes,
          cancel: cancel,
          txt: "确定将 " + obj.name + " 删除吗？"
        });
      }
    },
    async getPowerDelect(id) {
      return new Promise((resolve, reject) => {
        let success = data => {
          console.log(data.data);
          // 接口会返回1 或者[]
          if (data.data === 1) {
            resolve(true);
          }
          resolve(false);
        };
        let date = new Date();
        let dataTime =
          date.getFullYear() +
          "-" +
          (date.getMonth() + 1) +
          "-" +
          date.getDate() +
          " " +
          date.getHours() +
          ":" +
          date.getMinutes() +
          ":" +
          date.getSeconds();
        this.$ajax.get("api/school/checkSyllabus", {
          params: { class_id: id, start_time: dataTime },
          func: { success: success }
        });
      });
    },

    bindTempOrg(obj, obj1, obj3) {
      this.addForm.base_id = obj.base_id;
      this.addForm.status = obj.status;
      if (parseInt(obj.level) === 4) {
        //修改
        this.addForm.id = obj.id;
        this.addForm.pid = obj.pid;
        this.addForm.name = obj.name;
      } else {
        //添加
        this.addForm.id = 0;
        this.addForm.name = "";
        this.addForm.pid = obj.id;
      }
    },
    // deleteOrg_confirm(obj) {
    //   let yes = (data) => {
    //     this.changeOrg(obj.id, 0);
    //   };
    //   let cancel = (data) => {};
    //   this.e_confirm({
    //     yes: yes,
    //     cancel: cancel,
    //     txt: "确定将 " + obj.name + " 删除吗？",
    //   });
    // },
    changeOrg_confirm(obj, status) {
      let yes = data => {
        this.changeOrg(obj.id, status);
      };
      let cancel = data => {};
      this.e_confirm({
        yes: yes,
        cancel: cancel,
        txt:
          "确定将 " +
          obj.name +
          " 设置为 " +
          this.status_arr[parseInt(status)] +
          " 吗？"
      });
    },
    changeOrg(id, status) {
      let success = data => {
        this.$message.success(data.msg);
        this.getOrgData();
      };
      this.$ajax.put(
        "api/org/change_org",
        { id: id, status: status },
        { func: { success: success } }
      );
    }
  }
};
</script>

<style lang="scss">
.zh-organization-single {
  .frame-manage {
    .frame-list {
      display: flex;
      height: 40px;
      line-height: 40px;
      background: #ddd;
      color: #000;
      text-align: center;

      li {
        flex: 1;
        box-sizing: border-box;

        &:nth-of-type(1) {
          flex: 0 0 50px;
        }
      }
    }

    .custom-tree-node {
      width: 100%;

      .frame-list {
        background: none;
        border-bottom: 1px solid #ddd;

        li {
          position: relative;
          border-left: 1px solid #ddd;

          &:last-child {
            border-right: 1px solid #ddd;
          }
        }

        img {
          display: inline-block;
          vertical-align: middle;
        }
      }
    }

    .el-tree-node__content {
      padding-left: 0 !important;
      height: auto;
    }

    .el-tree-node__content {
      li:nth-of-type(2) .ellips {
        text-align: left;
        padding-left: 20%;

        .gap {
          display: inline-block;
          width: 18px;
        }
      }
    }
  }
}
</style>
